import ConfigParser
import os.path
import re


class Singleton(type):
    """ This class implement the singleton pattern for other classes. """
    def __init__(mcs, *args):
        type.__init__(mcs, *args)
        mcs._instance = None

    def __call__(mcs, *args):
        if mcs._instance is None:
            mcs._instance = type.__call__(mcs, *args)
        return mcs._instance



class Config:
    
    __metaclass__ = Singleton
    def __init__(self):
        self.__filename = os.path.expanduser("~/.kochmorse")
        self.__options = {'lessontime': 5,
                          'countdown': 5,
                          'speed': 25,
                          'effspeed': 12,
                          'frequency': 750,
                          'volume': 0,
                          'lesson': 2,
                          'preferlast': False}


        if os.path.exists(self.__filename):
            self.load()
        else:
            self.save()


    def load(self):
        cfg = ConfigParser.SafeConfigParser()
        cfg.read([self.__filename])
        
        if not cfg.has_section('basic'):
            return

        for option in self.__options.keys():
            if not cfg.has_option('basic',option):
                continue
            if option in ['volume']:
                self.__options[option] = cfg.getfloat('basic', option)
            elif option in ['preferlast']:
                self.__options[option] = cfg.getboolean('basic', option)
            else:
                self.__options[option] = cfg.getint('basic', option)
                

    def save(self):
        cfg = ConfigParser.SafeConfigParser()
        cfg.read([self.__filename])
        
        if not cfg.has_section('basic'):
            cfg.add_section('basic')
        
        for (key, value) in self.__options.items():
            if key in ['volume']:
                value = str(float(value))
            elif key in ['preferlast']:
                value = str(bool(value))
            else:
                value = str(int(value))
            cfg.set('basic', key, value)

        cfg.write(open(self.__filename, "w"))
    

    def __getattr__(self, name):
        m = re.match("^opt_(.+)$", name)
        if not m: 
            return object.__getattribute__(self, name)
      
        return self.__options[m.group(1)]


    def __setattr__(self, name, value):
        m = re.match("^opt_(.+)$", name)

        if not m:
            self.__dict__[name] = value
        else: 
            self.__options[m.group(1)] = value
